package com.xiaowen.config.security;


import com.xiaowen.user.entity.User;
import com.xiaowen.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: yf-wenhao
 * Date: 2024/9/18
 * Time: 下午5:01
 */
@Component
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //认证之前
        SmsCodeAuthenticationToken token = (SmsCodeAuthenticationToken) authentication;
        //认证之前Principal存放的是手机号
        User userDetails = userService.findByPhone((String) token.getPrincipal(), token.getOrgName());
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("无法根据手机号获取用户信息");
        }
        //认证之后,此时将获取的userDetails存放进Principal
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(userDetails, null, token.getOrgName());
        smsCodeAuthenticationToken.setDetails(token.getDetails());
        return smsCodeAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
